package com.briup.utils;

import com.briup.service.UserService;
import lombok.SneakyThrows;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;

/**
 * 实例工厂类
 */
public class InstanceFactory {
    private static final HashMap<String, Object> instanceMap = new HashMap<>();

    static {
        // 从类路径下的bean.properties文件中读取配置信息
        try (InputStream in = InstanceFactory.class
                .getResourceAsStream("/bean.properties")) {
            Properties properties = new Properties();
            properties.load(in);

            // 遍历配置，创建对象
            for (String key : properties.stringPropertyNames()) {
                // 获取类名
                String className = properties.getProperty(key);
                // 通过反射创建对象，并放入到Map容器中
                Class<?> clazz = Class.forName(className);
                Object instance = clazz.getDeclaredConstructor().newInstance();
                instanceMap.put(key, instance);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @SneakyThrows
    public static UserService getUserService() {
        return Class.forName("com.briup.service.UserServiceImpl")
                .asSubclass(UserService.class)
                .getDeclaredConstructor()
                .newInstance();
    }

    @SneakyThrows
    public static Object getInstance(String key) {
        return instanceMap.get(key);
    }

    public static <T> T getInstance(String key, Class<T> clazz) {
        return clazz.cast(instanceMap.get(key));
    }
}
